package com.zhxs.nfcscan.view;

import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.tencent.mmkv.MMKV;
import com.zhxs.nfcscan.R;
import com.zhxs.nfcscan.base.app.AppActivity;
import com.zhxs.nfcscan.base.app.AppApplication;

import java.net.MalformedURLException;
import java.net.URL;

public class SettingsActivity extends AppActivity {
    private EditText etServerUrl;
    private MMKV mmkv;
    
    @Override
    protected int getLayoutId() {
        return R.layout.activity_settings;
    }
    
    @Override
    protected void initView() {
        // 初始化标题栏
        initTitleBar();
        
        // 初始化UI组件
        etServerUrl = findViewById(R.id.et_server_url);

        // 设置保存按钮点击事件
        findViewById(R.id.btn_save).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveServerUrl();
            }
        });
    }
    
    @Override
    protected void initData() {
        // 初始化MMKV
        mmkv = MMKV.defaultMMKV();
        
        // 加载保存的服务器地址
        loadServerUrl();
    }
    
    /**
     * 初始化标题栏
     */
    private void initTitleBar() {
        // 设置标题
        setTitle(getString(R.string.system_settings));
    }

    /**
     * 加载保存的服务器地址
     */
    private void loadServerUrl() {
        String savedUrl = mmkv.decodeString(AppApplication.KEY_SERVER_URL, AppApplication.DEFAULT_SERVER_URL);
        etServerUrl.setText(savedUrl);
    }
    
    /**
     * 保存服务器地址
     */
    private void saveServerUrl() {
        String serverUrl = etServerUrl.getText().toString().trim();
        
        // 校验URL格式
        if (TextUtils.isEmpty(serverUrl)) {
            Toast.makeText(this, getString(R.string.server_url_empty), Toast.LENGTH_SHORT).show();
            return;
        }
        
        if (!isValidUrl(serverUrl)) {
            Toast.makeText(this, getString(R.string.server_url_invalid), Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 保存到MMKV
        mmkv.encode(AppApplication.KEY_SERVER_URL, serverUrl);
        
        Toast.makeText(this, getString(R.string.save_success), Toast.LENGTH_SHORT).show();
        
        // 延迟返回上一页
        etServerUrl.postDelayed(new Runnable() {
            @Override
            public void run() {
                finish();
            }
        }, 1000);
    }
    
    /**
     * 校验URL格式是否有效
     */
    private boolean isValidUrl(String url) {
        try {
            new URL(url);
            return true;
        } catch (MalformedURLException e) {
            return false;
        }
    }
    
    /**
     * 获取当前保存的服务器地址
     */
    public static String getServerUrl() {
        MMKV mmkv = MMKV.defaultMMKV();
        return mmkv.decodeString(AppApplication.KEY_SERVER_URL, AppApplication.DEFAULT_SERVER_URL);
    }
}
